from flask import request, jsonify
from api.db.services.seedAgent_service import seed_agentService, data_rulesService
import time
from datetime import datetime
from flask_login import login_required

def get_json_result(code=0, message="success", data=None):
    response = {"code": code, "message": message, "data": data}
    return jsonify(response)

def get_data_error_result(code=500, message=None, data=None):
    response = {"code": code, "message": message, "data": data}
    return jsonify(response)

def convert_to_timestamp(date_input):
    """将日期字符串或时间戳转换为Unix时间戳（秒级）"""
    if isinstance(date_input, (int, float)):
        return int(date_input)
    elif isinstance(date_input, str):
        try:
            dt = datetime.fromisoformat(date_input.replace('Z', '+00:00'))
            return int(dt.timestamp())
        except ValueError:
            try:
                dt = datetime.strptime(date_input, "%Y-%m-%d")
                return int(dt.timestamp())
            except ValueError:
                raise ValueError(f"无法解析日期格式: {date_input}")
    else:
        raise TypeError("输入必须是字符串或数字时间戳")

@manager.route('/seed_agent/create', methods=['POST'])
@login_required
def create_seed_agent():
    """创建新的SeedAgent"""
    data = request.json
    try:
        required_fields = ['purpose', 'data_source']
        if not all(field in data for field in required_fields):
            return get_data_error_result(code=400, message="缺少必要字段: purpose和data_source")
        
        # 自动添加时间和日期
        current_ts = int(time.time())
        current_dt = datetime.now()
        data['create_time'] = current_ts
        data['create_date'] = current_dt
        data['update_time'] = current_ts
        data['update_date'] = current_dt
        
        agent = seed_agentService.create_agent(data)
        return get_json_result(data={"agent_id": agent['agent_id']})
    except Exception as e:
        return get_data_error_result(message=str(e))

@manager.route('/seed_agent/delete', methods=['POST'])
@login_required
def delete_seed_agent():
    """删除SeedAgent"""
    data = request.json
    try:
        if 'agent_id' not in data:
            return get_data_error_result(code=400, message="缺少agent_id参数")
            
        success = seed_agentService.delete_agent(data['agent_id'])
        if success:
            return get_json_result(data=True)
        return get_data_error_result(code=404, message="Agent不存在")
    except Exception as e:
        return get_data_error_result(message=str(e))

@manager.route('/seed_agent/list', methods=['POST'])
@login_required
def list_seed_agents():
    """查询SeedAgent列表"""
    data = request.json
    try:
        # 处理日期范围
        create_start = data.get('create_start')
        create_end = data.get('create_end')
        update_start = data.get('update_start')
        update_end = data.get('update_end')
        
        # 构建查询参数
        query_params = {
            'purpose': data.get('purpose'),
            'data_source': data.get('data_source'),
            'knowledge_base': data.get('knowledge_base'),
            'importance_min': data.get('importance_min'),
            'importance_max': data.get('importance_max'),
            'create_start': convert_to_timestamp(create_start) if create_start else None,
            'create_end': convert_to_timestamp(create_end) if create_end else None,
            'update_start': convert_to_timestamp(update_start) if update_start else None,
            'update_end': convert_to_timestamp(update_end) if update_end else None,
            'sort_field': data.get('sort_field', 'create_time'),
            'sort_order': data.get('sort_order', 'desc'),
            'page': int(data.get('page', 1)),
            'per_page': int(data.get('per_page', 10))
        }
        
        result = seed_agentService.query_agents(query_params)
        return get_json_result(data=result)
    except Exception as e:
        return get_data_error_result(message=str(e))
    
@manager.route('/seed_agent/update', methods=['POST'])
@login_required
def update_seed_agent():
    """更新SeedAgent信息"""
    data = request.json
    try:
        if not data or 'agent_id' not in data:
            return get_data_error_result(code=400, message="请求体不能为空且必须包含agent_id")
        
        # 自动更新时间和日期
        current_ts = int(time.time())
        current_dt = datetime.now()
        data['update_time'] = current_ts
        data['update_date'] = current_dt
        
        updated = seed_agentService.update_agent(data['agent_id'], data)
        if updated:
            return get_json_result(data=True)
        return get_data_error_result(code=404, message="Agent不存在或未更新")
    except Exception as e:
        return get_data_error_result(message=str(e))
    
@manager.route('/seed_agent/detail', methods=['POST'])
@login_required
def get_seed_agent_detail():
    """获取SeedAgent详情"""
    data = request.json
    try:
        if 'agent_id' not in data:
            return get_data_error_result(code=400, message="缺少agent_id参数")
            
        agent = seed_agentService.get_agent_detail(data['agent_id'])
        if agent:
            return get_json_result(data=agent)
        return get_data_error_result(code=404, message="Agent不存在")
    except Exception as e:
        return get_data_error_result(message=str(e))

@manager.route('/data_rules/create', methods=['POST'])
@login_required
def create_data_rule():
    """创建新的DataRule"""
    data = request.json
    try:
        required_fields = ['agent_id', 'available_data']
        if not all(field in data for field in required_fields):
            return get_data_error_result(code=400, message="缺少必要字段: agent_id和available_data")
        
        # 自动添加时间和日期
        current_ts = int(time.time())
        current_dt = datetime.now()
        data['create_time'] = current_ts
        data['create_date'] = current_dt
        data['update_time'] = current_ts
        data['update_date'] = current_dt
        
        rule = data_rulesService.create_rule(data)
        return get_json_result(data={"rule_id": rule['rule_id']})
    except Exception as e:
        return get_data_error_result(message=str(e))

@manager.route('/data_rules/delete', methods=['POST'])
@login_required
def delete_data_rule():
    """删除DataRule"""
    data = request.json
    try:
        if 'rule_id' not in data:
            return get_data_error_result(code=400, message="缺少rule_id参数")
            
        success = data_rulesService.delete_rule(data['rule_id'])
        if success:
            return get_json_result(data=True)
        return get_data_error_result(code=404, message="Rule不存在")
    except Exception as e:
        return get_data_error_result(message=str(e))

@manager.route('/data_rules/list', methods=['POST'])
@login_required
def list_data_rules():
    """查询DataRules列表"""
    data = request.json
    try:
        # 校验必须参数
        if 'agent_id' not in data or not data['agent_id']:
            return get_json_result(code=400, message="agent_id is required")
        
        # 设置分页默认值
        current = max(1, int(data.get('current', 1)))
        page_size = max(1, min(int(data.get('pageSize', 10)), 100))
        
        # 提取其他查询条件
        query_params = {
            'agent_id': data['agent_id'],
            'page': current,
            'per_page': page_size
        }
        # 可选：添加其他查询条件
        if 'keyword' in data:
            query_params['keyword'] = data['keyword']
        if 'status' in data:
            query_params['status'] = data['status']
        
        result = data_rulesService.get_rules_by_agent(query_params)
        return get_json_result(data=result)
        
    except ValueError:
        return get_json_result(code=400, message="Invalid pagination parameters")
    except Exception as e:
        return get_data_error_result(message="Internal server error")
    
@manager.route('/data_rules/update', methods=['POST'])
@login_required
def update_data_rule():
    """更新DataRule信息"""
    data = request.json
    try:
        if not data or 'rule_id' not in data:
            return get_data_error_result(code=400, message="请求体不能为空且必须包含rule_id")
        
        # 自动更新时间和日期
        current_ts = int(time.time())
        current_dt = datetime.now()
        data['update_time'] = current_ts
        data['update_date'] = current_dt
        
        updated = data_rulesService.update_rule(data['rule_id'], data)
        if updated:
            return get_json_result(data=True)
        return get_data_error_result(code=404, message="Rule不存在或未更新")
    except Exception as e:
        return get_data_error_result(message=str(e))
    
@manager.route('/data_rules/detail', methods=['POST'])
@login_required
def get_data_rule_detail():
    """获取DataRule详情"""
    data = request.json
    try:
        if 'rule_id' not in data:
            return get_data_error_result(code=400, message="缺少rule_id参数")
            
        rule = data_rulesService.get_rule_detail(data['rule_id'])
        if rule:
            return get_json_result(data=rule)
        return get_data_error_result(code=404, message="Rule不存在")
    except Exception as e:
        return get_data_error_result(message=str(e))
    
@manager.route('/data_rules/batch_query', methods=['POST'])
@login_required
def batch_query_data_rules():
    """批量查询DataRules"""
    data = request.json
    try:
        rule_ids = data.get('rule_ids', [])
        if not rule_ids:
            return get_data_error_result(code=400, message="缺少rule_ids参数")
            
        rules = data_rulesService.batch_get_rules(rule_ids)
        return get_json_result(data=rules)
    except Exception as e:
        return get_data_error_result(message=str(e))